package com.sayice.coursetable.logic.utils;

import android.content.Context;
import android.util.Log;

import com.sayice.coursetable.CourseTableApp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/**
 * 文件工具类
 */
public abstract class FileUtils {
    /**
     * 保存字符串（已存在文件会覆盖内容）
     *
     * @param fileName 文件名
     * @param text     字符串
     */
    public static void saveText(String fileName, String text) {
        try (FileOutputStream output = CourseTableApp.context.openFileOutput(fileName, Context.MODE_PRIVATE);
             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output))) {
            writer.write(text);
        } catch (IOException e) {
            Log.d("FileUtils", "保存字符串失败！");
            e.printStackTrace();
        }
    }

    /**
     * 读取文件内容
     *
     * @param fileName 文件名
     * @return 返回文件内容字符串，若文件不存在则返回 null
     */
    public static String getText(String fileName) {
        StringBuilder content = new StringBuilder();
        try (FileInputStream input = CourseTableApp.context.openFileInput(fileName);
             BufferedReader reader = new BufferedReader(new InputStreamReader(input))) {
            String text;
            while ((text = reader.readLine()) != null) {
                content.append(text);
            }
        } catch (FileNotFoundException e) {
            Log.d("FileUtils", "读取文件失败：找不到文件");
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content.toString();

//        ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
//        try (FileInputStream input = CourseTableApp.context.openFileInput(fileName)) {
//            int len;
//            byte[] b = new byte[8192];
//            while ((len = input.read(b)) > 0) {
//                baos.write(b, 0, len);
//            }
//        } catch (FileNotFoundException e) {
//            Log.d("FileUtils", "读取文件失败：找不到文件");
//            e.printStackTrace();
//            return null;
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        try {
//            baos.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return baos.toString();
    }
}
